from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.core import paginator
from django.core.mail import EmailMessage, EmailMultiAlternatives
from django.template.loader import get_template, render_to_string
from django.utils.html import strip_tags

from tickets.models import Ticket, Note
from tickets.forms import TicketsOwnedForm, CreateTicketForm, UserAddNoteForm, WorkerAddNoteForm
from tickets.lib import send_email


def worker_portal(request, ticket_id=None, t_status=None):
	if t_status is None:
		# get list of tickets for ticket list on left, exclude closed and resolved
		tl = Ticket.objects.exclude(status__in=[3, 4])
	else:
		# get list of tickets for ticket list on left, based on status
		tl = Ticket.objects.filter(status=t_status)
		if tl.count() == 0:
			tl = Ticket.objects.all()
	if ticket_id is None:
		# just grab the first ticket from the list
		t = tl[0]
	else:
		# if the user specified a ticket, pull it
		t = Ticket.objects.get(pk=ticket_id)
	f = WorkerAddNoteForm()
	return render_to_response('worker_portal.html', {
								'ticket_list': tl,
								'ticket_detail': t,
								'form': f
								}, context_instance=RequestContext(request) )

def worker_add_note(request, ticket_id):
	t = get_object_or_404(Ticket, pk=ticket_id)
	# add note to a ticket (workers only)
	if request.method == 'POST':
		n = Note(ticket=t, action=1, submitter_email='it@missoulaboneandjoint.com')
		f = WorkerAddNoteForm(request.POST, instance=n)
		if f.is_valid():
			f.save()
			# send an email notifying everyone involved, excluding workers
			to_addresses = t.email_to_list()
			subject = 'New Note'
			location = request.build_absolute_uri(reverse('public_ticket_detail', args=(t.id,)))
			content = {	'header': 'New Note',
						'body': 'A note has been added to {ticket_name}.\nView it at <a href="{location}">{location}</a>'.format(
							location = location,
							ticket_name = t.title,
						),
			}
			send_email(
				to_addresses, 
				'it@missoulaboneandjoint.com', 
				subject, 
				content
			)
			return redirect(reverse('worker_portal_ticket', args=(t.id,)))
	else:
		# generate a new note form
		f = WorkerAddNoteForm()

	# get our ticket info for display
	tl = Ticket.objects.all()
	return render_to_response('worker_portal.html', {
								'ticket_list': tl,
								'ticket_detail': t,
								'form': f
								}, context_instance=RequestContext(request) )


def worker_ticket_hold(request, ticket_id):
	t = get_object_or_404(Ticket, pk=ticket_id)
	if request.method == 'POST':
		n = Note(ticket=t, action=2, submitter_email='it-helpdesk@missoulaboneandjoint.com')
		f = WorkerAddNoteForm(request.POST, instance=n)
		if f.is_valid():
			t.status = 2
			t.save()
			f.save()
			# send an email notifying everyone involved
			to_addresses = t.email_to_list()
			subject = 'Ticket Put On-Hold'
			location = request.build_absolute_uri(reverse('public_ticket_detail', args=(t.id,)))
			content = {	'header': 'Ticket Put On-Hold', 
						'body': '{ticket_name} has been put on hold.\nView it at <a href="{location}">{location}</a>'.format(
							location = location,
							ticket_name = t.title,
						),
			}
			send_email(
				to_addresses,
				'it@missoulaboneandjoint.com',
				subject,
				content
			)
			return redirect(reverse('worker_portal_ticket', args=(t.id,)))

	# generate a form to add a note to notify of the ticket status change
	n = Note(ticket=t)
	f = WorkerAddNoteForm(instance=n)
	return render_to_response('worker_update_ticket.html', {
								'ticket': t,
								'form': f,
								'action': 'Put Ticket On-Hold',
								'action_desc': 'Please enter the reason for putting the ticket on-hold',
								'action_url': 'hold',
								}, context_instance=RequestContext(request) )

def worker_ticket_unhold(request, ticket_id):
	t = get_object_or_404(Ticket, pk=ticket_id)
	t.status = 1
	t.save()
	n = Note(ticket=t, action=2, submitter_email='it-helpdesk@missoulaboneandjoint.com')
	n.comment = 'Ticket Taken Off Hold'
	n.save()
	return redirect(reverse('worker_portal_ticket', args=(t.id,)))


def worker_ticket_resolve(request, ticket_id):
	t = get_object_or_404(Ticket, pk=ticket_id)
	if request.method == 'POST':
		n = Note(ticket=t, action=3, submitter_email='it-helpdesk@missoulaboneandjoint.com')
		f = WorkerAddNoteForm(request.POST, instance=n)
		if f.is_valid():
			t.status = 3
			t.save()
			f.save()
			# send an email notifying everyone involved
			to_addresses = t.email_to_list()
			subject = 'Ticket Resolved'
			location = request.build_absolute_uri(reverse('public_ticket_detail', args=(t.id,)))
			content = {	'header': 'Ticket Resolved', 
						'body': '{ticket_name} has been completed.\nIf you feel the task has not been completed in full or needs further work, please follow the link below and re-open the ticket, making sure to leave a descriptive note about what needs to be done for the ticket to be complete.\nView it at <a href="{location}">{location}</a>'.format(
							location = location,
							ticket_name = t.title,
						),
			}
			send_email(
				to_addresses,
				'it@missoulaboneandjoint.com',
				subject,
				content
			)
			return redirect(reverse('worker_portal_ticket', args=(t.id,)))

	# generate a form to add a note to notify of the ticket status change
	n = Note(ticket=t)
	f = WorkerAddNoteForm(instance=n)
	return render_to_response('worker_update_ticket.html', {
								'ticket': t,
								'form': f,
								'action': 'Resolved',
								'action_desc': 'Please enter the reason for resolving the ticket',
								'action_url': 'resolve',
								}, context_instance=RequestContext(request) )

def worker_ticket_close(request, ticket_id):
	t = get_object_or_404(Ticket, pk=ticket_id)
	if request.method == 'POST':
		n = Note(ticket=t, action=4, submitter_email='it-helpdesk@missoulaboneandjoint.com')
		f = WorkerAddNoteForm(request.POST, instance=n)
		if f.is_valid():
			t.status = 4
			t.save()
			f.save()
			# send an email notifying everyone involved
			to_addresses = t.email_to_list()
			subject = 'Ticket Closed'
			location = request.build_absolute_uri(reverse('public_ticket_detail', args=(t.id,)))
			content = {	'header': 'Ticket Closed', 
						'body': '{ticket_name} has been closed.\nIf you feel this is in error, re-open the ticket after following the link. Make sure to leave a note describing why the ticket has been re-opened.\nView it at <a href="{location}">{location}</a>'.format(
							location = location,
							ticket_name = t.title,
						),
			}
			send_email(
				to_addresses,
				'it@missoulaboneandjoint.com',
				subject,
				content
			)
			return redirect(reverse('worker_portal_ticket', args=(t.id,)))

	# generate a form to add a note to notify of the ticket status change
	n = Note(ticket=t)
	f = WorkerAddNoteForm(instance=n)
	return render_to_response('worker_update_ticket.html', {
								'ticket': t,
								'form': f,
								'action': 'Close Ticket',
								'action_desc': 'Please enter the reason for closing the ticket',
								'action_url': 'close',
								}, context_instance=RequestContext(request) )

def worker_ticket_reopen(request, ticket_id):
	t = get_object_or_404(Ticket, pk=ticket_id)
	if request.method == 'POST':
		n = Note(ticket=t, action=5, submitter_email='it-helpdesk@missoulaboneandjoint.com')
		f = WorkerAddNoteForm(request.POST, instance=n)
		if f.is_valid():
			t.status = 1
			t.save()
			f.save()
			# send an email notifying everyone involved
			to_addresses = t.email_to_list()
			subject = 'Ticket Re-Opened'
			location = request.build_absolute_uri(reverse('public_ticket_detail', args=(t.id,)))
			content = {	'header': 'Ticket Re-Opened', 
						'body': '{ticket_name} has been re-opened.\nView it at <a href="{location}">{location}</a>'.format(
							location = location,
							ticket_name = t.title,
						),
			}
			send_email(
				to_addresses,
				'it@missoulaboneandjoint.com',
				subject,
				content
			)
			return redirect(reverse('worker_portal_ticket', args=(t.id,)))

	# generate a form to add a note to notify of the ticket status change
	n = Note(ticket=t)
	f = WorkerAddNoteForm(instance=n)
	return render_to_response('worker_update_ticket.html', {
								'ticket': t,
								'form': f,
								'action': 'Re-Open Ticket',
								'action_desc': 'Please enter the reason for re-opening the ticket',
								'action_url': 'reopen',
								}, context_instance=RequestContext(request) )

def worker_raise_priority(request, ticket_id):
	t = get_object_or_404(Ticket, pk=ticket_id)
	if t.priority <= 4:
		t.priority += 1
	t.save()
	return redirect(reverse('worker_portal_ticket', args=(t.id,)))

def worker_lower_priority(request, ticket_id):
	t = get_object_or_404(Ticket, pk=ticket_id)
	if t.priority >= 1:
		t.priority -= 1
	t.save()
	return redirect(reverse('worker_portal_ticket', args=(t.id,)))
